from rest_framework.views import APIView
from django.http import JsonResponse
from rest_framework import status
from .models import Article, ArticleSerializer
from django.db.models import Q


class ArticleCreateView(APIView):
    def post(self, request, format=None):
        # 手动设置 author 字段为默认值 1
        request.data['author'] = 1

        serializer = ArticleSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({"code": "200", "data": serializer.data, "message": "创建成功", "ok": "true"},
                                status=status.HTTP_200_OK)
        return JsonResponse({"code": "400", "data": serializer.errors, "message": "创建失败", "ok": "false"},
                            status=status.HTTP_400_BAD_REQUEST)


class ArticleListView(APIView):
    def get(self, request, format=None):
        articles = Article.objects.all().order_by('-update_time')
        serializer = ArticleSerializer(articles, many=True)
        return JsonResponse({"code": "200", "data": serializer.data, "message": "查询成功", "ok": "true"},
                            status=status.HTTP_200_OK)


class ArticleDetailView(APIView):
    def get_object(self, pk):
        try:
            return Article.objects.get(pk=pk)
        except Article.DoesNotExist:
            return None

    def get(self, request, pk, format=None):
        article = self.get_object(pk)
        if article is None:
            return JsonResponse({"code": "404", "data": None, "message": "文章不存在", "ok": "false"},
                                status=status.HTTP_404_NOT_FOUND)
        serializer = ArticleSerializer(article)
        return JsonResponse({"code": "200", "data": serializer.data, "message": "查询成功", "ok": "true"},
                            status=status.HTTP_200_OK)

    def put(self, request, format=None):
        pk = request.data.get('id')
        if not pk:
            return JsonResponse({"code": "400", "data": None, "message": "缺少文章ID", "ok": "false"},
                                status=status.HTTP_400_BAD_REQUEST)
        article = self.get_object(pk)
        if article is None:
            return JsonResponse({"code": "404", "data": None, "message": "文章不存在", "ok": "false"},
                                status=status.HTTP_404_NOT_FOUND)

        # 确保 author 字段不会被前端传回的数据覆盖
        request.data['author'] = article.author.id

        serializer = ArticleSerializer(article, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({"code": "200", "data": serializer.data, "message": "更新成功", "ok": "true"},
                                status=status.HTTP_200_OK)
        return JsonResponse({"code": "400", "data": serializer.errors, "message": "更新失败", "ok": "false"},
                            status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        article = self.get_object(pk)
        if article is None:
            return JsonResponse({"code": "404", "data": None, "message": "文章不存在", "ok": "false"},
                                status=status.HTTP_404_NOT_FOUND)
        article.delete()
        return JsonResponse({"code": "200", "data": None, "message": "删除成功", "ok": "true"},
                            status=status.HTTP_200_OK)


class ArticleSearchView(APIView):
    def get(self, request, format=None):
        query = request.query_params.get('q', '')
        if not query:
            return JsonResponse({"code": "400", "data": None, "message": "缺少查询参数", "ok": "false"},
                                status=status.HTTP_400_BAD_REQUEST)

        articles = Article.objects.filter(Q(title__icontains=query) | Q(content__icontains=query)).order_by('-update_time')
        serializer = ArticleSerializer(articles, many=True)
        return JsonResponse({"code": "200", "data": serializer.data, "message": "查询成功", "ok": "true"},
                            status=status.HTTP_200_OK)


class BlogArticleListView(APIView):
    def get(self, request, category_id=None, tag_id=None, *args, **kwargs):
        # 如果 category_id 是通过路径参数传递的，优先使用它
        if category_id:
            articles = Article.objects.filter(category_id=category_id).order_by('-update_time')
        # 如果 tag_id 是通过路径参数传递的，优先使用它
        elif tag_id:
            articles = Article.objects.filter(tags__id=tag_id).order_by('-update_time')
        else:
            # 如果没有路径参数，尝试从查询参数中获取 category_id 或 tag_id
            category_id = request.query_params.get('category', None)
            tag_id = request.query_params.get('tag', None)
            if category_id:
                articles = Article.objects.filter(category_id=category_id).order_by('-update_time')
            elif tag_id:
                articles = Article.objects.filter(tags__id=tag_id).order_by('-update_time')
            else:
                # 如果既没有路径参数也没有查询参数，返回所有文章
                articles = Article.objects.all().order_by('-update_time')

        # 序列化数据
        serializer = ArticleSerializer(articles, many=True)
        return JsonResponse({
            "code": 200,
            "message": "查询成功",
            "ok": True,
            "data": serializer.data
        })


class BlogArticleDetailView(APIView):
    def get_object(self, pk):
        try:
            return Article.objects.get(pk=pk)
        except Article.DoesNotExist:
            return None

    def get(self, request, pk, format=None):
        article = self.get_object(pk)
        if article is None:
            return JsonResponse({
                "code": 404,
                "message": "文章不存在",
                "ok": False,
                "data": None
            }, status=404)
        serializer = ArticleSerializer(article)
        return JsonResponse({
            "code": 200,
            "message": "查询成功",
            "ok": True,
            "data": serializer.data
        })